<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { ToolOutlined } from "@ant-design/icons-vue";
import {
  listEquipmentInfoByPage,
  addEquipmentInfo,
  updateEquipmentInfo,
  deleteEquipmentInfo,
} from "@/api/equipment";
import type {
  EquipmentInfo,
  EquipmentInfoQueryRequest,
  EquipmentInfoAddRequest,
  EquipmentInfoUpdateRequest,
} from "@/models/equipment";
import dayjs from "dayjs";

// 设备类型映射
const equipmentTypes = {
  1: "水表",
  2: "电表",
  3: "其他",
};

// 设备管理相关状态
const equipments = ref<EquipmentInfo[]>([]);
const equipmentTotal = ref(0);
const equipmentCurrentPage = ref(1);
const equipmentPageSize = ref(6);
const equipmentNameSearch = ref("");
const equipmentNumberSearch = ref("");
const equipmentIdSearch = ref("");
const dormitoryId = ref(null);
const equipmentLoading = ref(false);

// 设备编辑弹窗
const equipmentModalVisible = ref(false);
const equipmentModalTitle = ref("添加设备");
const editingEquipment = ref<EquipmentInfoUpdateRequest>({
  equipmentId: 0,
  equipmentName: "",
  equipmentNumber: "",
  dormitoryId: 0,
  typeName: 1,
});

// 获取设备列表
const fetchEquipments = async () => {
  equipmentLoading.value = true;
  try {
    const queryRequest: EquipmentInfoQueryRequest = {
      current: equipmentCurrentPage.value,
      pageSize: equipmentPageSize.value,
      equipmentName: equipmentNameSearch.value,
      equipmentNumber: equipmentNumberSearch.value,
      equipmentId: equipmentIdSearch.value
        ? parseInt(equipmentIdSearch.value)
        : undefined,
      dormitoryId: dormitoryId.value,
    };
    const res = await listEquipmentInfoByPage(queryRequest);
    if (res.data.code === 0) {
      equipments.value = res.data.data.records;
      equipmentTotal.value = res.data.data.total;
    } else {
      message.error("获取设备列表失败");
    }
  } catch (error) {
    message.error("获取设备列表失败");
  } finally {
    equipmentLoading.value = false;
  }
};

// 搜索设备
const onSearch = () => {
  equipmentCurrentPage.value = 1;
  fetchEquipments();
};

// 重置搜索
const handleReset = () => {
  equipmentNameSearch.value = "";
  equipmentNumberSearch.value = "";
  equipmentIdSearch.value = "";
  dormitoryId.value = 1;
  equipmentCurrentPage.value = 1;
  fetchEquipments();
};

// 处理分页变化
const handleEquipmentTableChange = (pagination: any) => {
  equipmentCurrentPage.value = pagination.current;
  equipmentPageSize.value = pagination.pageSize;
  fetchEquipments();
};

// 添加设备
const handleAddEquipment = () => {
  equipmentModalTitle.value = "添加设备";
  editingEquipment.value = {
    equipmentId: 0,
    equipmentName: "",
    equipmentNumber: "",
    dormitoryId: 0,
    typeName: 1,
  };
  equipmentModalVisible.value = true;
};

// 编辑设备
const handleEditEquipment = (record: EquipmentInfo) => {
  equipmentModalTitle.value = "编辑设备";
  editingEquipment.value = {
    equipmentId: record.equipmentId,
    equipmentName: record.equipmentName,
    equipmentNumber: record.equipmentNumber,
    dormitoryId: record.dormitoryId,
    typeName: record.typeName,
  };
  equipmentModalVisible.value = true;
};

// 保存设备
const handleSaveEquipment = async () => {
  try {
    if (
      !editingEquipment.value.equipmentName ||
      !editingEquipment.value.equipmentNumber
    ) {
      message.error("请填写完整信息");
      return;
    }

    if (editingEquipment.value.equipmentId === 0) {
      // 添加设备
      const res = await addEquipmentInfo(editingEquipment.value);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error(res.data.message || "添加失败");
      }
    } else {
      // 更新设备
      const res = await updateEquipmentInfo(editingEquipment.value);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error(res.data.message || "更新失败");
      }
    }
    equipmentModalVisible.value = false;
    fetchEquipments();
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除设备
const handleDeleteEquipment = async (record: EquipmentInfo) => {
  try {
    const res = await deleteEquipmentInfo(record.equipmentId);
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchEquipments();
    } else {
      message.error(res.data.message || "删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

onMounted(() => {
  fetchEquipments();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <tool-outlined />
        <span>设备信息管理</span>
      </div>
    </template>
    <template #extra>
      <a-space>
        <a-input-number
          v-model:value="equipmentIdSearch"
          placeholder="设备ID"
          style="width: 120px"
        />
        <a-input
          v-model:value="equipmentNameSearch"
          placeholder="设备名称"
          style="width: 150px"
        />
        <a-input
          v-model:value="equipmentNumberSearch"
          placeholder="设备编号"
          style="width: 150px"
        />
        <a-input
          v-model:value="dormitoryId"
          placeholder="宿舍Id"
          style="width: 150px"
        />
        <a-button type="primary" @click="onSearch">搜索</a-button>
        <a-button @click="handleReset">重置</a-button>
        <a-button type="primary" @click="handleAddEquipment">
          添加设备
        </a-button>
      </a-space>
    </template>

    <a-table
      :dataSource="equipments"
      :loading="equipmentLoading"
      :pagination="{
        total: equipmentTotal,
        current: equipmentCurrentPage,
        pageSize: equipmentPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleEquipmentTableChange"
    >
      <a-table-column
        key="equipmentId"
        title="设备ID"
        data-index="equipmentId"
      />
      <a-table-column
        key="equipmentName"
        title="设备名称"
        data-index="equipmentName"
      />
      <a-table-column
        key="equipmentNumber"
        title="设备编号"
        data-index="equipmentNumber"
      />
      <a-table-column
        key="dormitoryId"
        title="所属宿舍"
        data-index="dormitoryId"
      />
      <a-table-column
        key="typeName"
        title="设备类型"
        data-index="typeName"
        :customRender="({ text }) => equipmentTypes[text]"
      />
      <a-table-column
        key="createTime"
        title="创建时间"
        data-index="createTime"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')"
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <a-space>
            <a @click="handleEditEquipment(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个设备吗？"
              @confirm="handleDeleteEquipment(record)"
            >
              <a style="color: #ff4d4f">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <!-- 设备编辑弹窗 -->
    <a-modal
      v-model:visible="equipmentModalVisible"
      :title="equipmentModalTitle"
      @ok="handleSaveEquipment"
    >
      <a-form :model="editingEquipment" layout="vertical">
        <a-form-item label="设备名称" required>
          <a-input v-model:value="editingEquipment.equipmentName" />
        </a-form-item>
        <a-form-item label="设备编号" required>
          <a-input v-model:value="editingEquipment.equipmentNumber" />
        </a-form-item>
        <a-form-item label="所属宿舍" required>
          <a-input-number
            v-model:value="editingEquipment.dormitoryId"
            style="width: 100%"
            :min="1"
          />
        </a-form-item>
        <a-form-item label="设备类型" required>
          <a-select v-model:value="editingEquipment.typeName">
            <a-select-option :value="1">水表</a-select-option>
            <a-select-option :value="2">电表</a-select-option>
            <a-select-option :value="3">其他</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
